package com.boot.system.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.boot.system.entity.SysLog;
import com.boot.system.mapper.LogMapper;
import com.boot.system.service.LogService;
import com.boot.util.ConvertUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service("logService")
public class LogServiceImpl extends ServiceImpl<LogMapper, SysLog> implements LogService {

    @Override
    public Page<SysLog> getLogPage(Map<String, Object> queryParam) {
        // 参数构建
        int pageNum = (int) queryParam.getOrDefault("pageNum", 1);
        int pageSize = (int) queryParam.getOrDefault("pageSize", 10);
        // 查询条件
        QueryWrapper query = QueryWrapper.create().from(SysLog.class);
        if (ObjectUtil.isNotEmpty(queryParam.get("createTime"))) {
            //操作时间
            List<Object> timeList = ConvertUtil.objectToList(queryParam.get("createTime"));
            query.between("create_time", DateUtil.parse(timeList.get(0) + " 00:00:00").getTime(), DateUtil.parse(timeList.get(1) + " 23:59:59").getTime());
        }
        if (ObjectUtil.isNotEmpty(queryParam.get("username"))) {
            // 操作用户
            query.and(SysLog::getUsername).eq(queryParam.get("username"));
        }
        if (ObjectUtil.isNotEmpty(queryParam.get("func"))) {
            // 调用方法
            query.and(SysLog::getFunc).eq(queryParam.get("func"));
        }
        if (ObjectUtil.isNotEmpty(queryParam.get("requestUri"))) {
            // 请求接口
            query.and(SysLog::getRequestUri).eq(queryParam.get("requestUri"));
        }
        if (ObjectUtil.isNotEmpty(queryParam.get("ip"))) {
            // IP地址
            query.and(SysLog::getIp).eq(queryParam.get("ip"));
        }
        if (ObjectUtil.isNotEmpty(queryParam.get("status"))) {
            // 状态
            query.and(SysLog::getStatus).eq(queryParam.get("status"));
        }
        query.orderBy((String) queryParam.getOrDefault("orderBy", "id desc"));
        return this.page(new Page<>(pageNum, pageSize), query);
    }

    @Override
    public boolean deleteLog(String ids) {
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        return this.mapper.deleteByIds(idList) > 0;
    }

    @Override
    public boolean clearLog(int day) {
        long time = System.currentTimeMillis();
        if (day > 0) {
            time = DateUtil.offsetDay(new Date(), -day).getTime();
        }
        return this.mapper.clear(time) > 0;
    }
}




